<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 汪利东,2016-04-19 13:44
// +----------------------------------------------------------------------

namespace Delivery\Controller;


use Common\Model\SettingModel;

class DeliveryController extends BaseController
{
    public function detail()
    {
        $map['delivery_id'] = I('get.id');
        $data = D('DeliveryMy')->relation(true)->where($map)->find();
        $this->data = $data;
        $this->display();
    }

    //确认收货
    public function confirmDelivery()
    {
        $map['delivery_id'] = I('get.delivery_id');


//        $borrow_num = new SettingModel();
//        $borrow_num = $borrow_num->getValue('borrow_num');
////        $order_id=M('order_delivery')->where($map)
////        M('')

        $OD = M('OrderDelivery');
        $OD->startTrans();
        $r = $OD->where($map)->setField('state_order', 3);
        if ($r) {
            $d = $OD->where($map)->find();
            $rr = M('Order_book')->where(['order_id' => $d['order_id']])->data(['state_order' => '3'])->save();
            // todo 待测试
            $Score = D("Score");
            $order = M('order_book')->where(['order_id' => $d['order_id']])->find();
            if ($order['type']) {
              // 借书
                $Score->addscore($order['user_id'], "6");
            } else {
                // 买书
                $number = M('order_has_book')->where(['order_id' => $order['order_id']])->count('quantity');
                $Score->addscore($order['user_id'], "5", $number);
            }
            if ($rr) {
                $OD->commit();
                die(json_encode(['code' => 1]));
            } else {
                $OD->rollback();
                die(json_encode(['code' => 0, 'msg' => '操作失败']));
            }
        } else {
            $OD->rollback();
            die(json_encode(['code' => 0, 'msg' => '操作失败']));
        }
    }

    //查看用户借书
    public function borrow()
    {
        $user_id = I('get.user_id');
        if (!empty($user_id)) {
            $map['b.user_id'] = I('get.user_id');
        }
        $card_id = I('get.card_id');
        if (!empty($card_id)) {
            $map['c.card_id'] = I('get.card_id');
        }
        $map['a.type'] = 1;
        $map['a.is_backed'] = 0;
        $map['b.state_order'] = ['neq', 0];
        $data = M('view_order_has_book')->alias('a')
            ->join('inner join order_book b on b.order_id=a.order_id')
            ->join('inner join card c on c.user_id=a.user_id')
            ->where($map)
            ->field("a.*")
            ->select();

        $this->data = $data;
        $this->user_id = $map['b.user_id'];

//        dump(M('view_order_has_book')->getLastSql());die;

        $this->display();
    }

    /**
     * 归还
     */
    public function broken()
    {
        $order_has_book_id = I('get.order_has_book_id');
        $data = D('OrderHasBook')->relation(true)->where(['order_has_book_id' => $order_has_book_id])->find();
        $this->data = $data;
//        dump($data);die;
        $this->display();
    }

    //直接归还
    public function doBack(){
        $recycle['man_id'] = I("session.xhsd_delivery_")['delivery_man']['man_id'];
        $recycle['num'] = I('post.num');
        $recycle['type'] = '0';
        $recycle['money'] = '0';
        $recycle['addtime'] = time();

        $map['order_has_book_id'] = I('post.order_has_book_id');
        $num = I('post.num');
        $result['code'] = 0;

        $r = M('order_has_book')->where($map)->find();
        $stateOrder = M("order_book")->where(['order_id'=>$r['order_id']])->getField("state_order");//查订单状态
        $recycle['book_id'] = $r['book_id'];
        if ($r['is_backed'] == 1 || ($r['quantity'] == ($r['num_backed'] + $r['num_broken']))) {
            $result['msg'] = '已归还';
        } elseif ($r['quantity'] > ($r['num_backed'] + $r['num_broken'] + $num)) {
            $result['msg'] = '本次归还数量超过总量';
        } elseif ($stateOrder != 3) {
            $result['msg'] = '该订单还未收货';
        } else {
            $r = M('order_has_book')->where($map)->setInc('num_backed', $num);
            if ($r['quantity'] <= ($r['num_backed'] + $r['num_broken'])) {
                M('order_has_book')->where($map)->setField('is_backed', 1);
            }
            M("recycle")->add($recycle);
            $result['code'] = 1;
            $result['msg'] = '成功';
        }
        echo json_encode($result);
    }

    //破损归还
    public function brokenBack(){
        $post = I("post.");

        $recycle['man_id'] = I("session.xhsd_delivery_")['delivery_man']['man_id'];
        $recycle['num'] = I('post.num');
        $recycle['type'] = '1';
        $recycle['addtime'] = time();
        $recycle['money'] = $post["money"];

        if(!empty($post["is_broken"]) && $post["is_broken"]=="on"){ //是否破损
            $post["is_broken"] = 1;
        }
        $map['order_has_book_id'] = $post["order_has_book_id"];
        $Orderhb = D('OrderHasBook');
        $r = $Orderhb->relation(true)->where($map)->find();
        $stateOrder = M("order_book")->where(['order_id'=>$r['order_id']])->getField("state_order");//查订单状态
        if($stateOrder != 3) {
            $result['code'] = 0;
            $result['msg'] = '该订单还未收货';
            echo json_encode($result);
            exit;
        }

        $recycle['book_id'] = $r['book_id'];

        $list["order_id"] = $r["order_id"];
        $list["book_id"] = $r["book_id"];
        $list["money_original"] = $r["book"]["dj"];
        $list["money"] = $post["money"];

        $Orderhb->startTrans();
        $Orderhb->where($map)->setInc("num_broken",1);  //破损数量+1
        $ur = $Orderhb->where($map)->find();
        $result['code'] = 0;
        if($ur['num_broken'] != $r['num_broken']+1){    //如果破损数量没有成功+1
            $result['msg'] = $r['num_broken']."系统错误,回收失败".$ur['num_broken'];
        }
        if($ur['quantity'] < $ur['num_broken']+$ur['num_backed']){ //如果归还数量+破损数量 > 购买数量
            $result['msg'] = "回收失败,已有图书归还或回收";
        }
        if($ur['quantity'] == $ur['num_broken']+$ur['num_backed']){ //如果已全部归来，修改归还状态为已归还
            $rr=$Orderhb->where($map)->data(["is_backed"=>1])->save();
            if(!$rr){
                $result['msg'] = "系统错误,回收失败,无法更新状态";
            }
        }
        $summary = "线下破损书回收，回收图书列表:订单号:".$list['order_id'].",id:".$list['book_id'].",原价:".$list['money_original'].",回收价:".$list['money'].";";
        //创建破损订单
        $map_pay=[
            "user_id"=>$r["order_book"]['user_id'],
            "status"=>1,
            "type"=>5,
            "way"=>"cash",
            "summary"=>$summary,
            "money"=>$list["money"],
            "money_real"=>$list["money"],
            "money_zero"=>0
        ];
        $pay_id=M("Pay")->data($map_pay)->add();
        if(!$pay_id){
            $result['msg'] = "系统错误";
        }
        $dataList= [
            'order_id'=>$list['order_id'],
            'book_id'=>$list['book_id'],
            "user_id"=>$r["order_book"]['user_id'],
            "money"=>$list["money"],
            "money_original"=>$list["money"],
            "state_order"=>1,
            "pay_id"=>$pay_id
        ];
        $r=M("Order_broken")->add($dataList);
        if($r){
            $Orderhb->commit();


            M("recycle")->add($recycle);
            $result['code'] = 1;
            $result['msg'] = "回收成功";
        }else{
            $Orderhb->rollback();
            $result['msg'] = "系统错误";
        }
        echo json_encode($result);

    }
}